const http = require('http')

const qs=require('querystring')

const config=require('../config')

const getAllannouncement = async (ctx) => { //请求最新八条公告
    const result = new Promise( (resolve,reject) => {
        let lang=ctx.cookies.get('lang')||'zh_CN',langid=0
        if(lang=='zh_CN'){
            langid=0
        }else if(lang=='zh_TW'){
            langid=1
        }else if(lang=='en_US'){
            langid=2
        }
        let opt={
            hostname:config.hostname,
            port: config.port,
            path:`/announcement/query/${langid}`,
            method: "GET"
        }
        let req=http.request(opt,(res) => {
            res.setEncoding('utf8');
            let data = ''
            res.on('data', (chunk) => {
                data += chunk
            });
            res.on('end', () => {
                resolve(JSON.parse(data).data)
            })
        })
        req.on('error', (e) => {
            reject(e)
        })
        //写入数据到请求主体
        req.end()
    })
    return result
}

const queryAnnouncementById = async (ctx) => { //根据ID查询公告详情
    let id=ctx.params.id,lang=ctx.cookies.get('lang')||'zh-CN',langid=0
    if(!isNaN(Number(id))){
        if(lang=='zh_CN'){
            langid=0
        }else if(lang=='zh_TW'){
            langid=1
        }else if(lang=='en_US'){
            langid=2
        }
        const result = new Promise( (resolve,reject) => {
            let opt={
                hostname:config.hostname,
                port: config.port,
                path:`/announcement/query/id/${id}/${langid}`,
                method: "GET"
            }
            let req=http.request(opt,(res) => {
                res.setEncoding('utf8');
                let data = ''
                res.on('data', (chunk) => {
                    data += chunk
                });
                res.on('end', () => {
                    resolve(JSON.parse(data).data)
                })
            })
            req.on('error', (e) => {
                reject(e)
            })
            //写入数据到请求主体
            req.end()
        })
        return result
    }else{
        return null
    }
}

module.exports={
    getAllannouncement,
    queryAnnouncementById
}